/**
 * 汉王门禁设备
 */
var pageBean = null;
var dataList = {};
var spaces = {};
var spaceRooms = {};
var rooms = {};
var connectStatusAll = {'1':'已连接','2':'未连接'};
$(document).ready(function(e) {
	
	$("#btnDeviceAdd").click(add);
	$("#btnSave").click(save);
	$("#btnCancle").click(cancle);
	$("#spaceIdForm").change(spaceFormChange);
	initialSpace();
	search(1);
	
})
//更新桉树空间工作人员的门禁信息
function updateEmployee(){
	var spaceId = $("#searchSpaceId").val();
	if(spaceId == '0'){
		alert('请选择空间');
		return;
	}
	$.ajax({
        url: '/euc/hanwang/bindemployee/'+spaceId,
        data:'',//JSON.stringify(hanWangDoor),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	alert(datas.message); 	
        },
        error: function () {
        	console.log("/euc//bindemployee/"+spaceId+" error");
        }
    });
	
}

//更新桉树空间门禁管理员信息
function updateManager(){
	var spaceId = $("#searchSpaceId").val();
	if(spaceId == '0'){
		alert('请选择空间');
		return;
	}
	$.ajax({
        url: '/euc/hanwang/updateManager/'+spaceId,
        data:'',//JSON.stringify(hanWangDoor),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	alert(datas.message); 	
        },
        error: function () {
        	console.log("/euc/hanwang/updateManager/"+spaceId+" error");
        }
    });
	
}

function add(){
	$("#operator").html("添加");
	clearForm();
	$("#btnSave").unbind();
	$("#btnSave").click(save);
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataForm']").show();
}

function clearForm(){
	$("[formParameter='hanWangDoor']").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			var name = $(element).attr("name");
			if(tagName == 'SELECT'){
				var firstVal = $(element).find('option').eq(0).val();				
				$(element).val(firstVal).trigger('change');
			}else{
				$(element).val('');
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function setForm(hanWangDoor){
	$("[formParameter='hanWangDoor']").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			var name = $(element).attr("name");
			if(tagName != 'SELECT'){
				$(element).val(hanWangDoor[name]);
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	$("#spaceIdForm").val(hanWangDoor["spaceId"]).trigger('change');
	spaceFormChange();
	$("#roomIdForm").val(hanWangDoor["roomId"]).trigger('change');
	
}

function main(id){	
	var hanWangDoor = dataList[id];
	hanWangDoor['main'] = true;
	$.ajax({
        url: '/euc/hanwang/main',
        data:JSON.stringify(hanWangDoor),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	search(pageBean.currentPage);
            	alert(datas.message);
        	}else{
        		alert(datas.message);
        	}        	
        },
        error: function () {
        	console.log("/euc/hanwang/main error");
        }
    });
}

function notmain(id){	
	var mhanWangDoor = dataList[id];
	mhanWangDoor['main'] = false;
	updateHanWangDoor(mhanWangDoor);
}


function common(id){	
	var hanWangDoor = dataList[id];
	hanWangDoor['common'] = true;
	$.ajax({
        url: '/euc/hanwang/update',
        data:JSON.stringify(hanWangDoor),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	search(pageBean.currentPage);
            	alert(datas.message);
        	}else{
        		alert(datas.message);
        	}        	
        },
        error: function () {
        	console.log("/euc/hanwang/main error");
        }
    });
}

function notcommon(id){	
	var mhanWangDoor = dataList[id];
	mhanWangDoor['common'] = false;
	updateHanWangDoor(mhanWangDoor);
}

function deleteData(id){	
	$.ajax({
        url: '/euc/hanwang/delete',
        data:JSON.stringify({'id':id}),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	search(pageBean.currentPage);
            	alert(datas.message);
        	}else{
        		alert(datas.message);
        	}        	
        },
        error: function () {
        	console.log("/euc/hanwang/delete error");
        }
    });
}

function detail(id){	
	clearForm();
	setForm(dataList[id]);
	$("#operator").html("编辑");
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataForm']").show();	
	$("#btnSave").unbind();
	$("#btnSave").click(function(){
		var mHanWang = dataList[id];
		update(mHanWang);
	});
}

function update(hanWangDoor){
	if(hanWangDoor == null){
		return false;
	}
	hanWangDoor = getRequestJson(hanWangDoor);
	if(hanWangDoor == false){
		return false;
	}
	updateHanWangDoor(hanWangDoor);	
}

function updateHanWangDoor(hanWangDoor){
	$.ajax({
        url: '/euc/hanwang/update',
        data:JSON.stringify(hanWangDoor),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	search(pageBean.currentPage);
        	}else{
        		alert(datas.message);
        	}        	
        },
        error: function () {
        	console.log("/euc/contracttemplate/update error");
        }
    });
}

function getRequestJson(hanWangDoor){	
	if(hanWangDoor == null){
		hanWangDoor = {};
	}
	$("[formParameter='hanWangDoor']").each(function(index,element){		
		try{			
			var required = $(element).prop("required");				
			var name = $(element).attr("name");	
			var val =  $(element).val();
			if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
				var message = $(element).attr("message");
				alert(message);
				hanWangDoor = false;
				return false;
			}
			if(name == 'roomId'){
				if(val != 0){
					hanWangDoor[name] = val;
					hanWangDoor['roomName'] = $(this).find('option[value='+val+']').text();
				}else{
					hanWangDoor[name] = val;
					hanWangDoor['roomName'] = '';
				}
			}else if(name == 'spaceId'){
				hanWangDoor['spaceName'] = $(this).find('option[value='+val+']').text();
				hanWangDoor[name] = val;
			}else{
				hanWangDoor[name] = val;
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	return hanWangDoor;
}

function save(){
	var requestJson = {};
	requestJson = getRequestJson(requestJson);
	if(requestJson == false){
		return false;
	}
	
	$.ajax({
        url: '/euc/hanwang/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	console.log(JSON.stringify(datas));
        	if(datas.status == 0){
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	search(pageBean.currentPage);
        	}else{
        		alert(datas.message);
        	}        	
        },
        error: function () {
        	console.log("/euc/hanwang/add error");
        }
    });
}

function cancle(){
	$("DIV[name='dataList']").show();
	$("DIV[name='dataForm']").hide();
}

function getSearchParameter(currentPage){
	try{
		var deviceName= $.trim($("input[name='parameter']").val());
		var connectStatus= $("#searchConnectStatus").val();
		var spaceId= $("#searchSpaceId").val();
		if(connectStatus == '0'){
			connectStatus = '';
		}
		if(spaceId == '0'){
			spaceId = '';
		}
		var requestJson = {'like':{'deviceName':deviceName},'equals':{'spaceId':spaceId,'connectStatus':connectStatus}}
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
	return false;	
}


function search(currentPage){

	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		return false;
	}
	var requestJson = {currentPage:currentPage,data:requestJson}; 
	$.ajax({
        url: '/euc/hanwang/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	console.log(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();	        	
        	$.each(result.data.list,function(i,data){
                var html = '<tr>';
                html += '<td style="width:160px;">' + $.trim(data.spaceName) + '</td>';
                html += '<td>' + $.trim(data.deviceName) + '</td>';
                html += '<td>' + $.trim(data.deviceNumber) + '</td>';
                if(data.connectStatus == 1 ){
                	html += '<td>' + $.trim(connectStatusAll[data.connectStatus]) + '</td>';
                }else{
                	html += '<td><font color="red">' + $.trim(connectStatusAll[data.connectStatus]) + '</font></td>';
                }                
                html += '<td>' + $.trim(data.ip) + '</td>';
                html += '<td>' + $.trim(data.port) + '</td>';
                html += '<td>' + $.trim(data.roomName) + '</td>';
                html += '<td>' + $.trim(data.lastConnectTime) + '</td>';                
                if(data.main == true){
                	html += '<td>是</td>';
                }else{
                	html += '<td>否</td>';
                }
                
                if(data.common == true){
                	html += '<td>是</td>';
                }else{
                	html += '<td>否</td>';
                }
                
                html += '<td style="width:240px;">';
                if(data.main == false){
                	html += '<a href="javascript:main('+data.id+');" class="tablelink">设置主设备</a>&nbsp;&nbsp;&nbsp;';                	
                }else{
                	html += '<a href="javascript:notmain('+data.id+');" class="tablelink">取消主设备</a>&nbsp;&nbsp;&nbsp;';
                }
                
                if(data.common == false){
                	html += '<a href="javascript:common('+data.id+');" class="tablelink">设置公共设备</a>&nbsp;&nbsp;&nbsp;';                	
                }else{
                	html += '<a href="javascript:notcommon('+data.id+');" class="tablelink">取消公共设备</a>&nbsp;&nbsp;&nbsp;';
                }
                
                html += '<a href="javascript:detail('+data.id+');" class="tablelink">编辑</a>&nbsp;&nbsp;&nbsp;';
                html += '<a href="javascript:deleteData('+data.id+');" class="tablelink">删除</a>&nbsp;&nbsp;&nbsp;</td>';
                html += '</tr>';
                $("#userTable").append(html);
                dataList[data.id] = data;   
			});
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log("/euc/hanwang/query error");
        }  
    });
}

function initailPageNumber(totalPage,currentPage,pageLength){
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){console.log(e.messge);}	
}

/*空间名称*/
function initialSpace(){
	try{
		var spaceString = $.trim(localStorage.getItem('space'));
		if(spaceString == ''){
			$.ajax({
		        url: '/euc/system/space',
		        data:'',
		        beforeSend: function(request) {
		        	var accessToken = localStorage.getItem('accessToken');
		            request.setRequestHeader("accessToken",accessToken );
		        },
		        dataType: 'JSON',
		        async: true,
		        contentType:'application/json;charset=utf-8',
		        type: 'POST',
		        success: function (result, textStatus, response) {
		        	try{
		        		var spaceId = $("SELECT[name='spaceId']");
			        	$.each(result,function(index,data){	
			        		$('<option value="'+ data.id +'">'+ data.spaceName +'</option>').appendTo($(spaceId));
			        		spaces[data.id] = data;  
			   			});
			        	var spaceJson = JSON.stringify(spaces);
			        	localStorage.setItem('space',spaceJson);
		        	}catch(e){
		        		console.log(e.message);
		        	}
		        },
		        error: function () {
		        	console.log("/euc/system/space error");
		        }
		    });
		}else{
			spaces = $.parseJSON(spaceString);
			var spaceId = $("SELECT[name='spaceId']");
			$.each(spaces,function(key,space){
				$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceId));
			});
		}		
	}catch(e){
		console.log(e.messge);
	}
}

/*根据空间查询房间列表*/
function spaceFormChange(){
	var spaceIdSelected=$("#spaceIdForm").children('option:selected').val();
	try{
		rooms = spaceRooms[spaceIdSelected];
		var requestJson = {'spaceId':spaceIdSelected};
		if(rooms == null){
			$.ajax({
		        url: '/euc/hanwang/spaceroom',
		        data:JSON.stringify(requestJson),
		        beforeSend: function(request) {
		        	var accessToken = localStorage.getItem('accessToken');
		            request.setRequestHeader("accessToken",accessToken );
		        },
		        dataType: 'JSON',
		        async: false,
		        contentType:'application/json;charset=utf-8',
		        type: 'POST',
		        success: function (result, textStatus, response) {
		        	try{
		        		var myRooms = {};
		        		var roomIdForm = $("#roomIdForm");
		        		$(roomIdForm).empty();
		        		$('<option value="0" selected>请选择</option>').appendTo($(roomIdForm));
			        	$.each(result,function(index,data){
			        		$('<option value="'+ data.id +'">'+ data.roomName +'</option>').appendTo($(roomIdForm));
			        		myRooms[data.id] = data;  
			   			});
			        	spaceRooms[spaceIdSelected] = myRooms;
		        	}catch(e){
		        		console.log(e.message);
		        	}
		        },
		        error: function () {
		        	console.log("/euc/hanwang/spaceroom error");
		        }
		    });
		}else{			
			var roomIdForm = $("#roomIdForm");
			$(roomIdForm).empty();
    		$('<option value="0" selected>请选择</option>').appendTo($(roomIdForm));
			$.each(rooms,function(key,room){
				$('<option value="'+ room.id +'">'+ room.roomName +'</option>').appendTo($(roomIdForm));
			});
		}		
	}catch(e){
		console.log(e.messge);
	}
}




